import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:mall/constant/app_dimens.dart';

import 'package:mall/gen/r.dart';
import 'package:mall/utils/network_change_sc/network_change_sc.dart';
import 'package:mall/utils/sc/load_state_model.dart';
import 'package:mall/utils/sc/state_controller.dart';

class WrappedListPlaceholderComponent extends StatelessWidget {
  const WrappedListPlaceholderComponent({
    super.key,
    required this.sc,
    this.emptyWidget = const EmptyPlaceholderWidget(), //自定义空数据占位图
    this.errorWidget = const ErrorPlaceholderWidget(),
    this.netErrorWidget = const NetErrorPlaceholderWidget(),
    this.loadingWidget = const LoadingPlaceholderWidget(),
    // required this.child,
  });
  //子组件
  // final Widget child;
  //列表数据状态控制器
  final ListSC sc;
  //空数据占位图
  final Widget? emptyWidget;
  //网络错误占位图
  final Widget? errorWidget;
  //请求错误占位图
  final Widget? netErrorWidget;
  //加载中占位图
  final Widget? loadingWidget;

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      return PlaceholderComponent(
        isVisible: sc.data.isEmpty,
        loadState: sc.loadState.value,
        emptyWidget: emptyWidget,
        errorWidget: errorWidget,
        netErrorWidget: netErrorWidget,
        loadingWidget: loadingWidget,
        onReNetWorkToDo: () => sc.refreshData(),
        // child: child,
      );
    });
  }

  //返回要显示的组件
  static Widget widget<T>({
    required ListSC<T> sc,
    emptyWidget = const EmptyPlaceholderWidget(), //自定义空数据占位图
    errorWidget = const ErrorPlaceholderWidget(),
    netErrorWidget = const NetErrorPlaceholderWidget(),
    loadingWidget = const LoadingPlaceholderWidget(),
    required Widget Function(List<T>) builder,
  }) {
    if (sc.data.isEmpty) {
      return PlaceholderComponent(
        isVisible: sc.data.isEmpty,
        loadState: sc.loadState.value,
        emptyWidget: emptyWidget,
        errorWidget: errorWidget,
        netErrorWidget: netErrorWidget,
        loadingWidget: loadingWidget,
        onReNetWorkToDo: () => sc.refreshData(),
      );
    } else {
      return builder.call(sc.data);
    }
  }

  //返回要显示的组件
  static Widget widget1<T>({
    required LoadStateType state,
    required T? data,
    required Widget Function(T) builder,
    Function()? onReNetWorkToDo,
    emptyWidget = const EmptyPlaceholderWidget(), //自定义空数据占位图
    errorWidget = const ErrorPlaceholderWidget(),
    netErrorWidget = const NetErrorPlaceholderWidget(),
    loadingWidget = const LoadingPlaceholderWidget(),
  }) {
    //判断 data 是否是数组
    var isVisible = false;
    if (data == null) {
      isVisible = true;
    } else if (data is List) {
      isVisible = data.isEmpty;
    } else if (data is String) {
      isVisible = data.isEmpty;
    } else if (data is Map) {
      isVisible = data.isEmpty;
    }

    if (isVisible) {
      return PlaceholderComponent(
        isVisible: true,
        loadState: state,
        emptyWidget: emptyWidget,
        errorWidget: errorWidget,
        netErrorWidget: netErrorWidget,
        loadingWidget: loadingWidget,
        onReNetWorkToDo: onReNetWorkToDo,
      );
    } else {
      return builder.call(data!);
    }
  }
}

class PlaceholderComponent extends StatefulWidget {
  const PlaceholderComponent({
    super.key,
    // required this.child,
    required this.isVisible,
    required this.loadState,
    this.emptyWidget = const EmptyPlaceholderWidget(), //自定义空数据占位图
    this.errorWidget = const ErrorPlaceholderWidget(),
    this.netErrorWidget = const NetErrorPlaceholderWidget(),
    this.loadingWidget = const LoadingPlaceholderWidget(),
    this.onReNetWorkToDo,
  });

  //子组件
  // final Widget child;
  //状态控制器
  final bool isVisible;
  //传入数据加载状态
  final LoadStateType loadState;
  //空数据占位图
  final Widget? emptyWidget;
  //网络错误占位图
  final Widget? errorWidget;
  //请求错误占位图
  final Widget? netErrorWidget;
  //加载中占位图
  final Widget? loadingWidget;
  //网络恢复,抛出,让外部重新刷新数据
  final Function()? onReNetWorkToDo;

  @override
  State<PlaceholderComponent> createState() => _PlaceholderComponentState();
}

class _PlaceholderComponentState extends State<PlaceholderComponent> {
  //网络状态C
  final networkC = Get.put(NetworkChangeSC());

  Worker? worker;

  @override
  void initState() {
    super.initState();
    //自动刷新数据
    worker = ever(networkC.hasNetWork, (callback) {
      if (networkC.hasNetWork.value && widget.isVisible && widget.loadState == LoadStateType.refreshError()) {
        widget.onReNetWorkToDo?.call();
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    worker?.call();
  }

  @override
  Widget build(BuildContext context) {
    //判断当前是否有数据
    if (!widget.isVisible) {
      return const SizedBox.shrink();
    } else {
      // Widget placeholderWidget = widget.child;
      Widget placeholderWidget = const SizedBox.shrink();
      widget.loadState.when(
        initial: () => null,
        refreshIng: () => null,
        refreshSuccess: () {
          // 请求成功后,数据为空,显示空数据占位图
          if (widget.emptyWidget != null) {
            placeholderWidget = widget.emptyWidget!;
          }
        },
        //请求错误
        refreshError: () {
          //并且网络异常的情况下,显示网络异常占位图
          if (!networkC.hasNetWork.value) {
            if (widget.netErrorWidget != null) {
              placeholderWidget = widget.netErrorWidget!;
            }
          } else {
            //其他异常错误,显示错误占位图
            if (widget.errorWidget != null) {
              placeholderWidget = widget.errorWidget!;
            }
          }
        },
        loadMoreIng: () => null,
        loadMoreSuccess: (hasMore) => null,
        loadMoreError: () => null,
      );
      //不显示占位图,直接显示
      return placeholderWidget;
    }
  }
}

//空数据占位图
class EmptyPlaceholderWidget extends StatelessWidget {
  const EmptyPlaceholderWidget({
    super.key,
    this.desc = '暂无数据',
    this.height = 300,
  });

  //文案描述
  final String desc;
  //高度
  final double height;
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: height,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Image.asset(R.image.emptyImgVisitor),
          const SizedBox(
            height: 15,
          ),
          Text(
            desc,
            style: const TextStyle(
              fontSize: 14,
              color: Colors.black,
            ),
          ),
        ],
      ),
    );
  }
}

//加载中占位图
class LoadingPlaceholderWidget extends StatelessWidget {
  const LoadingPlaceholderWidget({super.key});
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(
            width: 30,
            height: 30,
            child: CircularProgressIndicator(
              backgroundColor: Colors.grey.withAlpha(33),
              strokeWidth: 3,
            )),
        const SizedBox(height: 12),
        const Text('数据加载中...',
            style: TextStyle(
              fontSize: 14.0, // 字体大小
              color: Colors.grey, // 设置字体颜色
              decoration: TextDecoration.none, // 设置不显示下划线
            ))
      ],
    );
  }
}

//网络错误占位图
class NetErrorPlaceholderWidget extends StatelessWidget {
  const NetErrorPlaceholderWidget({super.key});
  @override
  Widget build(BuildContext context) {
    return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      Image.asset(
        R.image.emptyImg,
        height: 75,
        width: 75,
      ),
      SizedBox(height: 12),
      Text('Oops…断网了',
          style: TextStyle(
            fontSize: 14.0,
            color: Colors.black,
            decoration: TextDecoration.none,
          )),
      SizedBox(height: 12),
      Text('网络已飞去外太空，请检查当前网络状态',
          style: TextStyle(
            fontSize: 12.0,
            decoration: TextDecoration.none,
          )),
      SizedBox(height: 12),
      // AppDefaultButton(
      //   title: '立即检查',
      //   width: 100,
      //   height: 40,
      //   radis: 20,
      //   action: () {
      //     if (Platform.isAndroid) {
      //       AppSettings.openAppSettings(type: AppSettingsType.wireless);
      //     } else {
      //       openAppSettings();
      //     }
      //   },
      // )
    ]);
  }
}

//加载失败占位图
class ErrorPlaceholderWidget extends StatelessWidget {
  const ErrorPlaceholderWidget({super.key, this.retryCallback});

  final VoidCallback? retryCallback;
  @override
  Widget build(BuildContext context) {
    return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      // const Icon(Icons.cached_rounded, size: 100, color: Colors.yellow),
      const SizedBox(height: 12),
      const Text('加载失败...',
          style: TextStyle(
            fontSize: 14.0,
            color: Colors.grey,
            decoration: TextDecoration.none,
          )),
      const SizedBox(height: 12),
      GestureDetector(
        onTap: () {
          retryCallback?.call();
        },
        child: const Text('稍后重试',
            style: TextStyle(fontSize: 14.0, color: Color(0XFF4A90E2), decoration: TextDecoration.none)),
      )
    ]);
  }
}
